package com.narbeshuber.tablet.lasalara.http;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.narbeshuber.tablet.lasalara.LasaLaraActivity;
import com.narbeshuber.tablet.lasalara.fragment.BookFragment;
import com.narbeshuber.tablet.lasalara.model.Book;

public class DeleteBookTask extends AsyncTask<String, Object, String> {

	LasaLaraActivity lasalaraActivity;
	ProgressDialog dialog;

	public DeleteBookTask(LasaLaraActivity lasalaraActivity) {
		this.lasalaraActivity = lasalaraActivity;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = ProgressDialog.show(lasalaraActivity, "",
				"Deleting book. Please wait...", true);
	}

	@Override
	protected String doInBackground(String... params) {
		try {

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
					"http://1.narbeshuber.appspot.com/delete");

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("k", params[0]));
			nameValuePairs.add(new BasicNameValuePair("pk", params[1]));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			httpclient.execute(httppost);
			
			lasalaraActivity.getDbHelper().beginTransaction();
			lasalaraActivity.getDbHelper().deleteBook(params[0]);
			lasalaraActivity.getDbHelper().endTransaction();
			
		} catch (Exception e) {
			Log.d("Exception: ", e.getMessage());
		}

		return "";
	}
	
	protected void onPostExecute(String result) {
		dialog.dismiss();
		
		lasalaraActivity.getDbHelper().beginTransaction();
		List<Book> books = lasalaraActivity.getDbHelper().getAllBooks();
		lasalaraActivity.getDbHelper().endTransaction();
		
		BookFragment.getInstance().getListAdapter().setBooks(books);
		BookFragment.getInstance().getListAdapter().refreshList();
	}

}
